package shapes.shapes2D.distribution 
{
	import flash.geom.Rectangle;
	import flash.geom.Point;
	/**
	 * ...
	 * @author Nicolas Barradeau
	 * http://en.nicoptere.net
	 */
	public class Frame
	{
		
		public var rect:Rectangle;
		public var x:Number;
		public var y:Number;
		public var width:Number;
		public var height:Number;
		public var colNum:int;
		public var rowNum:int;
		private var points:Vector.<Point>;
		
		public function Frame( rect:Rectangle, colNum:int = 5, rowNum:int = 5 ) 
		{
			
			this.rect = rect;
			this.x = rect.x;
			this.y = rect.y;
			
			this.width = rect.width;
			this.height = rect.height;
			
			this.colNum = colNum;
			this.rowNum = rowNum;
			
		}

		
		public function distribute( shuffle:Boolean = false, jitter:Number = 0 ):Vector.<Point>
		{
			
			var p:Point;
			points = new Vector.<Point>();
			var i:int =  colNum * rowNum, offsetX:Number, offsetY:Number, x:Number, y:Number, dx:Number, dy:Number;
			
			offsetX = width / colNum;
			offsetY = height / rowNum
			
			while ( i-- )
			{
				x = i % colNum;
				y = int( i / colNum );
				
				if ( x == 0 || x == colNum - 1 || y == 0 || y == rowNum - 1 )
				{
					
					dx = this.x + x * offsetX + offsetX / 2;
					dy = this.y + y * offsetY + offsetY / 2;
					
					p = new Point( dx, dy );
					
					points.push( p );
				}
			}
			
			if ( shuffle ) 	points.sort( this.shuffle );
			if ( jitter != 0 )	jitterPoints( jitter );
			
			return points;
			
		}
		
		private function shuffle( a:Number, b:Number ):int
		{
			return ( Math.random() > .5 ) ? 1 : -1;
		}

		private function jitterPoints( radius:Number ):void
		{
			var rad:Number;
			var angle:Number;
			for each( var p:Point in points )
			{
				
				rad = radius * Math.random();
				angle = ( 2 * Math.PI ) * Math.random();
				p.x += rad * Math.cos(angle);
				p.y += rad * Math.sin(angle);
				
			}
		}
		
	}

}